import React, { Component, useState, useEffect, useRef } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import CreateForm from './components/CreateForm';
import PersonInfo from './components/personInfo';
import { Button, Table, Divider, Dropdown, Menu, message, Form, Input, Select, Switch, Modal, Alert, Descriptions, Upload } from 'antd';
import { connect } from 'umi';
import axios from 'axios'

import { UploadOutlined } from '@ant-design/icons';
import { addRule } from './service';

const { Option } = Select
const { Search } = Input;

/**
 * 添加节点
 * @param fields
 */

const BasicForm = (props) => {
    const {
        loading,
        dispatch,
        formAndbasicForm: { list },
    } = props;
    const [current, setCurrent] = useState(null);//新建和编辑共用一个弹窗
    const [currentclass, setcurrentclass] = useState(null);//新建和编辑共用一个弹窗
    const [resetpassvisible, setpassvisible] = useState(false);//重置密码弹框
    const [createModalVisible, handleModalVisible] = useState(false);//新建用户弹框
    const [gradeVisible, setgradeVisible] = useState(false);//成绩查询弹框
    const [personVisible, setpersonVisible] = useState(false);//个人信息弹框
    const [updateModalVisible, handleUpdateModalVisible] = useState(false);
    const [stepFormValues, setStepFormValues] = useState({});
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);//选择列表
    const [data, setdata] = useState([]);//列表数据
    const [detail, setdetail] = useState({});//修改个人数据
    const [url, seturl] = useState('');

    let query = useRef({
        pageIndex: 1,
        pageSize: 20,
        name: "",
        order: "id desc"
    })
    useEffect(() => {
        seturl(window.location.host)

        dispatch({
            type: 'formAndbasicForm/fetch',
            payload: {
                ...query.current
            },
        });
    }, []);
    const paginationProps = {
        showSizeChanger: true,
        showQuickJumper: true,
        pageSize: query.current.pageSize,
        total: list.total,
        onChange: (pageIndex, pageSize) => {
            query.current = { ...query.current, pageIndex, pageSize }
            console.log(query.current)

            dispatch({
                type: 'formAndbasicForm/fetch',
                payload: {
                    ...query.current
                },
            });
            //   console.log(page,currents,pageSize,pagination)            
        },

        onShowSizeChange: (pageIndex, pageSize) => {
            query.current = { ...query.current, pageIndex, pageSize }
            dispatch({
                type: 'formAndbasicForm/fetch',
                payload: {
                    ...query.current
                },
            });
        }
    };
    const [form] = Form.useForm();
    const onFinish = async (values) => {
        const fieldsValue = await form.validateFields();
        console.log(fieldsValue)
        query.current = { ...query.current, ...fieldsValue }
        dispatch({
            type: 'formAndbasicForm/fetch',
            payload: {
                ...query.current
            },
        });
    };
    const columns = [
        {
            title: '班级代码',
            dataIndex: 'class_code',

        },

        {
            title: '年级',
            dataIndex: 'grade',
        },
        {
            title: '班级',
            dataIndex: 'class_name',
        },
        {
            title: '老师',
            dataIndex: 'teacher_name',
        },

        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => (
                <>
                    <a onClick={() => { setgradeVisible(true); setcurrentclass(record) }}>成员管理</a>
                    <Divider type="vertical" />
                    {/* 和新建界面一样，用同一个组件，这不过这个根据ID打开那边要获取值 */}
                    <a onClick={() => { handleModalVisible(true); setCurrent(record) }}>修改资料</a>
                    <Divider type="vertical" />

                    <Divider type="vertical" />
                    <a onClick={() => { del(record) }}>删除</a>

                </>
            ),
        },
    ];
    // 可以提交用户增加编辑信息
    const handleAdd = values => {
        console.log(values, current)
        const id = current ? current.id : undefined;
        dispatch({
            type: 'formAndbasicForm/submit',
            payload: {
                id,
                ...values,
            },
        });

    };
    const handleCancel = values => {
        handleModalVisible(false)
    }

    // 修改个人信息
    const changeinfo = (record) => {
        // 获取个人信息传到子组件

        console.log(record)
    };

    //筛选数据
    const onSelectChange = selectedRowKeys => {
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        setSelectedRowKeys(selectedRowKeys);
    };
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };

    // 删除
    const deleteItem = id => {
        dispatch({
            type: 'formAndbasicForm/submit',
            payload: {
                id,
            },
        });
    };
    const del = (currentItem) => {
        let str = ''
        if (currentItem) {
            str = currentItem.id
        } else {
            //字符串拼接
            if (selectedRowKeys.length==0) {
                message.error('当前没有选中用户')
                return

            }
            str = selectedRowKeys.join(',')
        }
        let content = currentItem? `删除的账户无法恢复，若非导入错误，建议使用账户冻结功能。\n确定要删除 ${currentItem.class_code +' __ '+currentItem.class_name} 吗？` : `本次选中 ${selectedRowKeys.length} 个班级，删除的账户无法恢复，若非导入错误，建议使用账户冻结功能。\n确定要删除吗？`
        Modal.confirm({
            title: '删除任务',
            content: content,
            okText: '确认',
            cancelText: '取消',
            onOk: () => deleteItem(str),
        });
    }
    // 导入
    const uploadprops = {
        name: 'file',
        showUploadList: false,
        accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel',
        beforeUpload: async file => {
            let config = {
                headers: {
                    'Content-Type': 'multipart/form-data',
                    'Authorization': `${sessionStorage.getItem('tokenHead')} ${sessionStorage.getItem('token')}`,
                },
            }
            const formData = new FormData();
            formData.append('file', file);
            axios.post('/class/importExcel', formData, config)
                .then(res => {
                    if (res.data.code == 200) {
                        message.success(`${file.name} 导入成功`);
                        dispatch({
                            type: 'formAndbasicForm/submit',
                            payload: {
                                id,
                            },
                        });
                    } else {
                        message.error(res.data.message)
                    }
                    console.log(res)
                })
                .catch(error => {
                    message.error(`file upload failed.`);
                });
        },

    };


    // 提示
    const onClose = (e) => {
        console.log(e, 'I was closed.');
    };



    const layout = {
        labelCol: {
            span: 10,
        },
        wrapperCol: {
            span: 10,
        },
    };
    const formRef = React.createRef();
    return (
        <PageHeaderWrapper>
            <div >

                {/* <Modal
                    title="个人信息"
                    visible={personVisible}
                    onOk={() => hidepersonModal(false)}
                    onCancel={() => hidepersonModal(false)}
                    okText="确认"
                    cancelText="取消"
                >
                    <Descriptions title="若信息有误请联系管理员" size='small'>
                        <Descriptions.Item label="账号">Cloud Database</Descriptions.Item>
                        <Descriptions.Item label="姓名" span={2}>Prepaid</Descriptions.Item>
                        <Descriptions.Item label="类型" >18:00:00</Descriptions.Item>
                        <Descriptions.Item label="工号">$80.00</Descriptions.Item>

                    </Descriptions>
                </Modal> */}

                <PersonInfo
                    currentclass={currentclass}
                    onCancel={() => setgradeVisible(false)}
                    modalVisible={gradeVisible}
                />
                <Form layout='inline'>
                    <Form.Item label="">
                        <Button type="primary" onClick={() => { handleModalVisible(true); setCurrent(null) }}>新建</Button>
                        {/* 增加 */}
                        {/* createform子组件 通过属性的方式传递本地父组件的增加方法和本地值 */}
                        <CreateForm
                            onSubmit={handleAdd}
                            onCancel={handleCancel}
                            current={current}
                            modalVisible={createModalVisible}
                        />
                    </Form.Item>

                    <Form.Item label="">
                        <Button type="primary" onClick={() => { del() }}>删除</Button>
                    </Form.Item>
                    <Form.Item label="">
                        <Upload {...uploadprops}>
                            <Button type="primary">
                                <UploadOutlined /> 班级导入
                           </Button>
                        </Upload>
                    </Form.Item>
                    <Form.Item label="">
                        <Button type="primary" >
                            <a href={`http://${url}/班级数据导入.xlsx`}>模板</a>
                        </Button>
                    </Form.Item>
                </Form>
            </div>
            <div style={{ marginTop: "50px", marginBottom: "20px" }}>
                <Form {...layout} layout='inline' form={form} name="control-ref" >

                    <Form.Item
                        style={{ width: '200px' }}
                        name="name"
                        label="关键字"

                    >

                        <Search
                            placeholder="班级代码，班级年级，班级名称，老师"
                            onSearch={onFinish}
                            style={{ width: 300 }}
                        />
                    </Form.Item>
                </Form>
            </div>
            <Alert
                message='如需变更班级信息，请联系管理员'
                type="warning"
                closable
                onClose={onClose}
            />
            <Table rowSelection={rowSelection} columns={columns} pagination={paginationProps} dataSource={list.list} rowKey={record => record.id} />
        </PageHeaderWrapper>
    )

}

export default connect(({ formAndbasicForm, loading }) => ({
    formAndbasicForm,
    loading: loading.models.formAndbasicForm,
}))(BasicForm);